<?php
function http_get($url,$headers=false){
    return http_exec($url,null,null,$headers);
}
function http_form($url, $data, $headers = false){
    if (!$headers) {
        $headers = array();
    }
    return http_exec($url, "POST", $data, $headers);
}
function http_body($url, $json, $headers = false){
    if (!$headers) {
        $headers = array();
    }
    $headers[] = "Content-Type: application/json; charset=UTF-8";
    return http_exec($url, "POST", json_encode($json), $headers);
}
function http_exec($url,$method=false,$str=false,$headers=false){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if($method){
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    }
    if($str){
        curl_setopt($curl, CURLOPT_POSTFIELDS, $str);
    }
    if ($headers) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_MAXREDIRS,5);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    $res = curl_exec($curl);
    curl_errno($curl);
    curl_close($curl);
    return $res;
}
function return_data($flag, $msg, $data = false)
{
    $res = array("flag" => $flag, "msg" => $msg);
    if ($data) {
        $res["data"] = $data;
    }
    return json_encode($res);
}
function auto_mk_dir()
{
    if (!is_dir(dirname(__FILE__) . "/db")) {
        mkdir(dirname(__FILE__) . "/db", 0777, true);
    }
}
function cache_key($key)
{
    return dirname(__FILE__) . '/db/file_cache_'.md5($key) . ".php";
}
function cache_set($key, $obj)
{
    auto_mk_dir();
    file_put_contents(cache_key($key), base64_decode("PD9waHAg") . json_encode($obj));
}
function cache_get($key)
{
    $file_name = cache_key($key);
    if(!file_exists($file_name)){
        return false;
    }
    $data = file_get_contents($file_name);
    if (!$data) {
        return false;
    }
    $data = substr($data, strlen(base64_decode("PD9waHAg")));
    return json_decode($data, true);
}
function cache_del($key){
    $file_name = cache_key($key);
    if(file_exists($file_name)){
        unlink($file_name);
    }
}
if($_GET["type"] == "1"){
    $data = cache_get("ali_path_id_".$_GET["path"]);
    if($data){
        echo return_data(true,"",$data["file_id"]);
        return;
    }
    echo return_data(false,"");
}else if($_GET["type"] == "2"){
    cache_set("ali_path_id_".$_GET["path"],array("file_id"=>$_GET["file_id"]));
    echo return_data(true,"");
}else if($_GET["type"] == "3"){
    $url = base64_decode($_GET["url"]);
    $method = $_SERVER["REQUEST_METHOD"];
    echo http_exec($url,$method,file_get_contents('php://input'));
}
